/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.business.service.impl;

import me.zhengjie.business.domain.Pggs;
import me.zhengjie.modules.system.domain.Dept;
import me.zhengjie.modules.system.domain.Role;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.DeptRepository;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.business.repository.PggsRepository;
import me.zhengjie.business.service.PggsService;
import me.zhengjie.business.service.dto.PggsDto;
import me.zhengjie.business.service.dto.PggsQueryCriteria;
import me.zhengjie.business.service.mapstruct.PggsMapper;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author xiahongbo
* @date 2022-06-07
**/
@Service
@RequiredArgsConstructor
public class PggsServiceImpl implements PggsService {

    private final PasswordEncoder passwordEncoder;
    private final UserRepository userRepository;
    private final PggsRepository pggsRepository;
    private final PggsMapper pggsMapper;

    private final DeptRepository deptRepository;
    private final RedisUtils redisUtils;
    @Override
    public Map<String,Object> queryAll(PggsQueryCriteria criteria, Pageable pageable){
        Page<Pggs> page = pggsRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(pggsMapper::toDto));
    }

    @Override
    public List<PggsDto> queryAll(PggsQueryCriteria criteria){
        return pggsMapper.toDto(pggsRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public PggsDto findById(String bisGsglId) {
        Pggs pggs = pggsRepository.findById(bisGsglId).orElseGet(Pggs::new);
        ValidationUtil.isNull(pggs.getBisGsglId(),"Pggs","bisGsglId",bisGsglId);
        return pggsMapper.toDto(pggs);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PggsDto create(Pggs resources) {
        // 新增护理机构，需要模拟用户插入
        User user = new User();
        user.setUsername(resources.getBisGsglYljgdm());
        user.setPassword(passwordEncoder.encode(DefaultUtil.PASSWORD));
        user.setNickName(resources.getBisGsglQymc());
        user.setPhone(resources.getBisGsglLxr());
        user.setEnabled(true);
        user.setIsAdmin(false);

        // 新增用户，模拟评估公司部门
        Dept dept = new Dept();
        dept.setPid(DefaultUtil.DEPT_PG);
        dept.setName(resources.getBisGsglQymc());
        dept.setEnabled(true);
        dept.setDeptSort(999);
        Dept newDept = deptRepository.save(dept);

        dept.setSubCount(0);
        // 计算子节点数目
        int count = deptRepository.countByPid(DefaultUtil.DEPT_PG);
        deptRepository.updateSubCntById(count, DefaultUtil.DEPT_PG);
        user.setDept(newDept);

        List<User> users = userRepository.findByRoleDeptId(DefaultUtil.DEPT_PG);
        // 删除数据权限
        redisUtils.delByKeys(CacheKey.DATA_USER, users.stream().map(User::getId).collect(Collectors.toSet()));
        redisUtils.del(CacheKey.DEPT_ID + DefaultUtil.DEPT_PG);

        // 新增用户，模拟评估公司角色
        Set<Role> setRole = new HashSet<Role>();
        Role role = new Role();
        role.setId(DefaultUtil.ROLE_PG);
        setRole.add(role);
        user.setRoles(setRole);

        user = userRepository.save(user);

        // 新增评估机构
        resources.setBisGsglId(IdUtil.simpleUUID());
        resources.setBisGsglUserId(newDept.getId());
        return pggsMapper.toDto(pggsRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Pggs resources) {
        Pggs pggs = pggsRepository.findById(resources.getBisGsglId()).orElseGet(Pggs::new);
        ValidationUtil.isNull( pggs.getBisGsglId(),"Pggs","id",resources.getBisGsglId());
        pggs.copy(resources);
        pggsRepository.save(pggs);
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String bisPggsId : ids) {
            pggsRepository.deleteById(bisPggsId);
        }
    }

    @Override
    public void download(List<PggsDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (PggsDto pggs : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}